package cn.btks.databasehandler.handle.service.impl;

import cn.btks.commonserver.pojo.PageList;
import cn.btks.commonserver.result.Constants;
import cn.btks.commonserver.result.ResultState;
import cn.btks.commonserver.result.StateInfo;
import cn.btks.commonserver.util.DateUtils;
import cn.btks.commonserver.util.JwtUtil;
import cn.btks.databasehandler.handle.pojo.BackUpConfig;
import cn.btks.databasehandler.handle.repository.BackUpConfigRepository;
import cn.btks.databasehandler.handle.service.BackUpConfigService;
import cn.btks.databasehandler.handle.util.QuartzUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import io.jsonwebtoken.Claims;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import java.sql.Time;
import java.util.*;

/**
 * @Author lijun
 * @Date 2020/12/28 12:07
 */
@Service
@Transactional
public class BackUpConfigServiceImpl implements BackUpConfigService {

    @Autowired
    BackUpConfigRepository backUpConfigRepository;

    @Autowired
    Scheduler scheduler;

    @Override
    public BackUpConfig findById(Long id) {
        Optional<BackUpConfig> optional = backUpConfigRepository.findById(id);
        if(optional.isPresent()){
            return optional.get();
        }
        return null;
    }

    @Override
    public List<BackUpConfig> findAllStartConfig() {
        return backUpConfigRepository.findAllByIsStarted(1);
    }

    @Override
    public ResultState findPagesByConfigNameAndConfigModeAndConfigCycle(Integer page, Integer pageSize, String configName, Integer configMode, Integer configCycle) {
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize);
        Specification<BackUpConfig> specification = new Specification<BackUpConfig>() {
            @Override
            public Predicate toPredicate(Root<BackUpConfig> root,
                                         CriteriaQuery<?> criteriaQuery,
                                         CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (!StringUtils.isEmpty(configName)) {
                    predicates.add(criteriaBuilder.like(root.get("configName"),
                            "%" + configName + "%"));
                }
                if (configMode != null) {
                    predicates.add(criteriaBuilder.equal(root.get("backUpMode"),configMode));
                }
                if (configCycle != null) {
                    predicates.add(criteriaBuilder.equal(root.get("backUpCycle"),
                            configCycle));
                }
                Predicate[] predicates1 = new Predicate[predicates.size()];
                return criteriaBuilder.and(predicates.toArray(predicates1));
            }
        };
        Page<BackUpConfig> configPage = backUpConfigRepository.findAll(specification, pageRequest);
        if(configPage.getTotalElements() > 0){
            PageList pageList = new PageList();
            pageList.setResult(configPage.getContent());
            pageList.setPageNum(configPage.getTotalPages());
            pageList.setTotalCount(configPage.getTotalElements());
            return new ResultState(StateInfo.FIND_OK.getCode(), StateInfo.FIND_OK.getMsg(), pageList);
        }
        return new ResultState(StateInfo.FIND_NULL.getCode(), StateInfo.FIND_NULL.getMsg());
    }

    @Override
    public ResultState save(BackUpConfig backUpConfig, HttpServletRequest request) throws Exception {
        String token = request.getHeader("token");
        Optional<Claims> optionalClaims = JwtUtil.getClaimsFromToken(token, JwtUtil.jwtsSecret);
        if(optionalClaims.isPresent()){
            Claims claims = optionalClaims.get();
            String name = claims.get("name").toString();
            Long userId =Long.valueOf(claims.get("id").toString());
            backUpConfig.setCreatedUserName(name);
            backUpConfig.setCreatedUserId(userId);
        }
        BackUpConfig byConfigName = backUpConfigRepository.findByConfigName(backUpConfig.getConfigName());
        if(byConfigName != null){
            return new ResultState(StateInfo.SAVE_ERROR_BACKUP_1.getCode(), StateInfo.SAVE_ERROR_BACKUP_1.getMsg());
        }
        String filePath = request.getSession(true).getServletContext().getRealPath("//") + Constants.BACKUPDB_FILE;
        System.out.println(filePath);
        if(backUpConfig != null && backUpConfig.getId() == null){
            Integer configBackUpCycle = backUpConfig.getBackUpCycle();
            String startDate = backUpConfig.getStartDate();
            String endDate = backUpConfig.getEndDate();
            Time startTime = backUpConfig.getStartTime();
            Map<String,String> timeMap = DateUtils.getTimeString(startTime);
            String cronStr = "";//cron定时字符串 0 0 23 L 12 ? 2019-2021
            switch (configBackUpCycle){
                case 0://年/次 0 0 23 L 12 ? 2019-2021
                    cronStr = timeMap.get("second") +" " + timeMap.get("minute") + " " + timeMap.get("hour") + " " + "L" + " 12 ? " +" " + startDate + "-" + endDate;
                    break;
                case 1://月/次 0 0 23 L 1-12 ? 2019-2021
                    cronStr = timeMap.get("second") +" " + timeMap.get("minute") + " " + timeMap.get("hour") + " " + "L" + " 1-12 ? " +" " + startDate + "-" + endDate;
                    break;
                case 2://日/次 0 0 23 1/1 1-12 ? 2019-2021
                    cronStr = timeMap.get("second") +" " + timeMap.get("minute") + " " + timeMap.get("hour") + " " + "1/1" + " 1-12 ? " +" " + startDate + "-" + endDate;
                    break;
                case 3: //周/次 0 59 23 ？ * 1 * |每周天23:59执行
                    cronStr = timeMap.get("second") +" " + timeMap.get("minute") + " " + timeMap.get("hour") + " " + "?" + " * " +backUpConfig.getWeekDay() + " " + startDate + "-" + endDate;
                    break;

            }
            backUpConfig.setBackUpCron(cronStr);
            backUpConfig.setIsStarted(1);
            BackUpConfig backUpConfig1 = backUpConfigRepository.save(backUpConfig);
            if(backUpConfig1 != null ){
                QuartzUtil.createScheduleJob(scheduler,backUpConfig1,filePath);
            }
            return backUpConfig1 != null ? new ResultState(StateInfo.SAVE_OK.getCode(), StateInfo.SAVE_OK.getMsg(), backUpConfig1) :
                    new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg());
        }
        return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg());
    }

    @Override
    public ResultState update(BackUpConfig backUpConfig, HttpServletRequest request) throws Exception {
        String token = request.getHeader("token");
        Optional<Claims> optionalClaims = JwtUtil.getClaimsFromToken(token, JwtUtil.jwtsSecret);
        if(optionalClaims.isPresent()){
            Claims claims = optionalClaims.get();
            String name = claims.get("name").toString();
            Long userId =Long.valueOf(claims.get("id").toString());
            backUpConfig.setCreatedUserName(name);
            backUpConfig.setCreatedUserId(userId);
        }
        String filePath = request.getSession(true).getServletContext().getRealPath("//") + Constants.BACKUPDB_FILE;
        if(backUpConfig.getId() != null){
            Optional<BackUpConfig> optional = backUpConfigRepository.findById(backUpConfig.getId());
            if(optional.isPresent()){
                Integer configBackUpCycle = backUpConfig.getBackUpCycle();
                String startDate = backUpConfig.getStartDate();
                String endDate = backUpConfig.getEndDate();
                Time startTime = backUpConfig.getStartTime();
                Map<String,String> timeMap = DateUtils.getTimeString(startTime);
                String cronStr = "";//cron定时字符串 0 0 23 L 12 ? 2019-2021
                switch (configBackUpCycle){
                    case 0://年/次 0 0 23 L 12 ? 2019-2021
                        cronStr = timeMap.get("second") +" " + timeMap.get("minute") + " " + timeMap.get("hour") + " " + "L" + " 12 ? " +" " + startDate + "-" + endDate;
                        break;
                    case 1://月/次 0 0 23 L 1-12 ? 2019-2021
                        cronStr = timeMap.get("second") +" " + timeMap.get("minute") + " " + timeMap.get("hour") + " " + "L" + " 1-12 ? " +" " + startDate + "-" + endDate;
                        break;
                    case 2://日/次 0 0 23 1/1 1-12 ? 2019-2021
                        cronStr = timeMap.get("second") +" " + timeMap.get("minute") + " " + timeMap.get("hour") + " " + "1/1" + " 1-12 ? " +" " + startDate + "-" + endDate;
                        break;
                    case 3: //周/次 0 59 23 ？ * 1 * |每周天23:59执行
                        cronStr = timeMap.get("second") +" " + timeMap.get("minute") + " " + timeMap.get("hour") + " " + "?" + " * " +backUpConfig.getWeekDay() + " " + startDate + "-" + endDate;
                        break;
                }
                backUpConfig.setBackUpCron(cronStr);
                BackUpConfig backUpConfig1 = backUpConfigRepository.save(backUpConfig);
                if(backUpConfig1 != null ){
                    QuartzUtil.updateScheduleJob(scheduler,backUpConfig1,filePath);
                }
                return backUpConfig1 != null ? new ResultState(StateInfo.SAVE_OK.getCode(), StateInfo.SAVE_OK.getMsg(), backUpConfig1) :
                        new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg());
            }
        }
        return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg());
    }

    @Override
    public int updateIsStarted(Long id, Integer isStarted) {
        Optional<BackUpConfig> optional = backUpConfigRepository.findById(id);
        if(optional.isPresent()){
            return backUpConfigRepository.updateIsStarted(id, isStarted);
        }
        return 0;
    }

    @Override
    public ResultState delete(Long id) {
        Optional<BackUpConfig> optional = backUpConfigRepository.findById(id);
        if(optional.isPresent()){
            int result = backUpConfigRepository.deleteByConfigId(id);
            if(result > 0){
                QuartzUtil.deleteScheduleJob(scheduler,optional.get().getConfigName());
            }
            return result > 0 ? new ResultState(StateInfo.DELETE_OK.getCode(), StateInfo.DELETE_OK.getMsg(), result) :
                    new ResultState(StateInfo.DELETE_ERROR.getCode(), StateInfo.DELETE_ERROR.getMsg());
        }
        return new ResultState(StateInfo.DELETE_ERROR_2.getCode(), StateInfo.DELETE_ERROR_2.getMsg());
    }
}
